type TileProvider = "geoq" | "baidu" | "gaode";
import L from "leaflet";

export function createGeoqTileLayer(
  style: "purplishBlue" | "community" | "warm" | "gray" = "gray"
) {
  const urls = {
    purplishBlue:
      "https://map.geoq.cn/ArcGIS/rest/services/ChinaOnlineStreetPurplishBlue/MapServer/tile/{z}/{y}/{x}",
    community:
      "https://map.geoq.cn/ArcGIS/rest/services/ChinaOnlineCommunity/MapServer/tile/{z}/{y}/{x}",
    warm: "https://map.geoq.cn/ArcGIS/rest/services/ChinaOnlineStreetWarm/MapServer/tile/{z}/{y}/{x}",
    gray: "https://map.geoq.cn/ArcGIS/rest/services/ChinaOnlineStreetGray/MapServer/tile/{z}/{y}/{x}"
  };

  return L.tileLayer(urls[style], {
    attribution: "© GeoQ",
    maxZoom: 16,
    subdomains: ["1", "2", "3", "4"]
  });
}

export function createBaiduTileLayer(
  layerType: "normal" | "satellite" = "normal"
) {
  const layerConfig = {
    normal: { style: "normal", subdomains: ["0", "1", "2", "3"] },
    satellite: {
      style: "time",
      subdomains: ["0", "1", "2", "3", "4", "5", "6", "7"]
    }
  };

  try {
    return L.tileLayer(
      `http://online{s}.map.bdimg.com/tile/?qt=tile&x={x}&y={y}&z={z}&styles=${layerConfig[layerType].style}`,
      {
        attribution: "© 百度地图",
        maxZoom: 19,
        subdomains: layerConfig[layerType].subdomains
      }
    );
  } catch (error) {
    console.error("百度地图初始化失败:", error);
    return null;
  }
}

export function createGaodeTileLayer(
  type: "vector" | "satellite" | "terrain" = "vector",
  options: {
    key?: string;
    subdomains?: string[];
    maxZoom?: number;
  } = {}
) {
  console.log("createGaodeTileLayer", type, options);
  const baseUrls = {
    vector:
      "https://webrd0{s}.is.autonavi.com/appmaptile?lang=zh_cn&size=1&scale=1&style=8&x={x}&y={y}&z={z}",
    satellite:
      "https://webst0{s}.is.autonavi.com/appmaptile?style=6&x={x}&y={y}&z={z}",
    terrain:
      "https://webst0{s}.is.autonavi.com/appmaptile?style=7&x={x}&y={y}&z={z}"
  };
  let layerOptions = {
    attribution: "© 高德地图",
    maxZoom: options.maxZoom || 18,
    subdomains: options.subdomains || ["1", "2", "3", "4"]
  };
  layerOptions = options
    ? { ...layerOptions, ...(options.key && { key: options.key }) }
    : layerOptions;
  console.log("layerOptions", layerOptions);
  return L.tileLayer(baseUrls[type], layerOptions);
}

// 统一导出方式
const TileLayers = {
  geoq: createGeoqTileLayer,
  baidu: createBaiduTileLayer,
  gaode: createGaodeTileLayer
};

export type { TileProvider };
export default TileLayers;
